import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:myflutter/ws/net/Connector.dart';
import 'package:flutter/services.dart';
import 'package:myflutter/ws/save/SharedPreferencesHelper.dart';
import 'package:myflutter/ws/scroll_behavior/NoScrollGlowOverscrollIndicator.dart';
import 'package:myflutter/ws/theme/MyColors.dart';
// import 'package:android_intent_plus/android_intent.dart';
// import 'package:android_intent_plus/flag.dart';



import 'noti/MyNotification.dart';
// import 'package:permission_handler/permission_handler.dart';



class GamePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return GamePageState();
  }
}

class GamePageState extends State<GamePage> {
  final Connector connector = Connector("ws://123.249.3.198:8765");
  final TextEditingController _textEditingController = TextEditingController();
  ScrollController _scrollController = ScrollController();
  List<Widget> _messages = [];
  bool connected = false;
  String _readySend = "";
  String _lastSend = "";
  String username = "";
  MyNotification gamePageNotification = MyNotification();

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("状态更新: " + state.name);
    if (state == AppLifecycleState.resumed) {
      // 应用从后台返回前台，自动重连 WebSocket

    }
  }

  void scrollToBottom() {
    print("滑动至新信息");
    _scrollController.animateTo(
      _scrollController.position.maxScrollExtent + 500,
      duration: Duration(milliseconds: 20),
      curve: Curves.easeInOut,);
  }

  @override
  Future<void> didChangeDependencies() async {
    super.didChangeDependencies();
    if (!connected) {
      var args = ModalRoute.of(context)!.settings.arguments;
      if (args != null) {
        args as Map<String, dynamic>;
        username = args['username'];
      } else {
        String get = await SharedPreferencesHelper.getString("name") as String;
        username = get;
      }

      connector.connect();
      connector.send(username);
      username += " ";
      connector.channel.stream.listen((message) async {
        if ('$message' != "你说: $_lastSend") {
          await gamePageNotification.showNotification('新消息', message, "scroll", scrollToBottom);
        }

        setState(() {
          print('$message');
          // scrollToBottom();

          if ('$message'.contains("加入了聊天") && '$message' != "你说: $_lastSend") {
            _messages.add(
                Text(message, style: TextStyle(
                  fontSize: 18, // 设置字体大小
                  fontFamily: "Arial", // 设置字体
                  fontWeight: FontWeight.bold, // 设置字体粗细
                  color: Colors.red, // 设置字体颜色
                ),)
            );
          } else if ('$message'.contains("退出了聊天") && '$message' != "你说: $_lastSend") {
            _messages.add(
                Text(message, style: TextStyle(
                  fontSize: 18, // 设置字体大小
                  fontFamily: "Arial", // 设置字体
                  fontWeight: FontWeight.bold, // 设置字体粗细
                  color: Colors.blue, // 设置字体颜色
                ),)
            );
          } else {
          _messages.add(
          Text(message, style: TextStyle(
          fontSize: 18, // 设置字体大小
          fontFamily: "Arial", // 设置字体
          fontWeight: FontWeight.bold, // 设置字体粗细
          // color: Colors.blue, // 设置字体颜色
          ),)
          );
          _messages.add(SizedBox(height: 20));
          }
          if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
            scrollToBottom();
          }
        });

      },
          onError: (error) {
            print("WebSocket error: $error");
            // 处理连接错误
          },
          onDone: () {
            print("WebSocket closed");
            // 处理连接关闭
          });
      connected = true;
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    // connector.channel.sink.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    double senderWidth =  MediaQuery
        .of(context)
        .size.width * 0.51;
    double senderHeight =  MediaQuery
        .of(context)
        .size.height * 0.07;
    // 添加此行以设置应用程序的屏幕方向
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp, // 仅允许纵向方向
      DeviceOrientation.portraitDown, // 仅允许纵向方向（倒置）
    ]);
    return Scaffold(
      // backgroundColor: Theme.of(context).primaryColor,
      appBar: AppBar(toolbarHeight: senderHeight,
          title: Text("当前名称：$username", style: TextStyle(fontSize: senderHeight * 0.4),),
          actions: [
        IconButton(
          icon: Icon(Icons.settings, size: senderHeight * 0.4 ,),
          onPressed: () {
            // 在这里添加按钮点击后的逻辑
            Navigator.pushNamed(context, '/name',);
          },
    ),
            SizedBox(width: 5,)
    ],),
      body: Center(
        child: Column(
          children: [
            Expanded(
              child: ScrollConfiguration(
                behavior: NoScrollGlowOverscrollIndicator(),
                child: SingleChildScrollView(
                  controller: _scrollController,
                  child: FocusScope(
                    child: Center(
                      child: Column(
                        children: _messages,
                      ),
                    ),
                  ),
                ),
              )

            ),
            SizedBox(height: 20),
            Container(
              width:  senderWidth,
              height: 60,
              child: TextField(
                controller: _textEditingController,// 将控制器传递给TextField
                decoration: InputDecoration(
                  hintText: "输入消息",
                ),
                onChanged: (text) {
                  setState(() {
                    _readySend = text;
                  });
                },
              ),
            ),
            Container(
              height: senderHeight,
              width:  senderWidth,
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: MyColors().getTimeColor(context),
                ),
                onPressed: () {
                  if (_readySend != ""){
                    _lastSend = _readySend;
                    connector.send(username + _readySend);
                  }
                  setState(() {
                    _readySend = "";
                    _textEditingController.clear();
                    scrollToBottom();
                    // 在发送消息后手动触发刷新
                  });
                },
                child: Text("发送", style: TextStyle(fontSize: senderHeight * 0.3),),
              ),
            ),
            SizedBox(height: 60),
          ],
        ),
      ),
    );
  }
}
